package com.atlassianstudio.confluence.htmldiff;

import org.outerj.daisy.diff.HtmlCleaner;
import org.outerj.daisy.diff.XslFilter;
import org.outerj.daisy.diff.html.HTMLDiffer;
import org.outerj.daisy.diff.html.HtmlSaxDiffOutput;
import org.outerj.daisy.diff.html.TextNodeComparator;
import org.outerj.daisy.diff.html.dom.DomTreeBuilder;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.AttributesImpl;

import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;
import java.util.Locale;

public class Util {
    public static String diffHTML(String oldHtml, String newHtml) throws Exception {
        StringWriter out = new StringWriter();
        StringReader oldin = new StringReader(oldHtml);
        StringReader newin = new StringReader(newHtml);
        SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler result = tf.newTransformerHandler();
        result.setResult(new StreamResult(out));

        XslFilter filter = new XslFilter();
        ContentHandler postProcess = filter.xsl(result, "com/atlassianstudio/confluence/htmldiff/htmlheader.xsl");
        Locale locale = Locale.getDefault();
        String prefix = "diff";

        HtmlCleaner cleaner = new HtmlCleaner();
        InputSource oldSource = new InputSource(oldin);
        InputSource newSource = new InputSource(newin);

        DomTreeBuilder oldHandler = new DomTreeBuilder();
        cleaner.cleanAndParse(oldSource, oldHandler);
        TextNodeComparator leftComparator = new TextNodeComparator(oldHandler, locale);
        DomTreeBuilder newHandler = new DomTreeBuilder();
        cleaner.cleanAndParse(newSource, newHandler);
        TextNodeComparator rightComparator = new TextNodeComparator(newHandler, locale);

        postProcess.startDocument();
        postProcess.startElement("", "diffreport", "diffreport", new AttributesImpl());
//                doCSS(css, postProcess);
        postProcess.startElement("", "diff", "diff", new AttributesImpl());
        HtmlSaxDiffOutput output = new HtmlSaxDiffOutput(postProcess, prefix);
        HTMLDiffer differ = new HTMLDiffer(output);
        differ.diff(leftComparator, rightComparator);
        System.out.print(".");
        postProcess.endElement("", "diff", "diff");
        postProcess.endElement("", "diffreport", "diffreport");
        postProcess.endDocument();
        return out.toString();
    }
}